package com.david.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DesUtil {
    //密钥偏移向量（CBC模式）
    private static byte[] iv1 = { (byte) 0x22, (byte) 0xE2, (byte) 0x31,(byte) 0x75, (byte) 0x00, (byte) 0xC1, (byte) 0xF2, (byte) 0x22 };

    public static String decrypt(String decryptString, String decryptKey)
            throws Exception {
        IvParameterSpec iv = new IvParameterSpec(iv1);
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, iv);

        return new String(cipher.doFinal(Base64.decodeBase64(decryptString)));
    }

    public static String encrypt(String encryptString, String encryptKey)
            throws Exception {
        IvParameterSpec iv = new IvParameterSpec(iv1);
        DESKeySpec dks = new DESKeySpec(encryptKey.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        return Base64.encodeBase64String(cipher.doFinal(encryptString.getBytes()));
    }

    /**
     * MD5加密
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String md5(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest=MessageDigest.getInstance("MD5");
        byte[] results=messageDigest.digest(str.getBytes());
        return bytesToHex(results);
    }

    /**
     * 二进制转十六进制
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
            if(num < 0) {
                num += 256;
            }
            if(num < 16){
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }

    /**
     * 利用Apache的工具类实现SHA-256加密
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String sha256Encrypt(String str) throws NoSuchAlgorithmException, CloneNotSupportedException, UnsupportedEncodingException {
        MessageDigest messageDigest= MessageDigest.getInstance("SHA-256");
        String sysEncoding=System.getProperty("file.encoding");
        byte[] hash = messageDigest.digest(str.getBytes(sysEncoding));
        messageDigest.clone();
        return Base64.encodeBase64String(hash);
    }
}
